<template>
  <div>
    <div class="flex items-center">
      <el-button type="primary" @click="AddWeb = true">创建快照</el-button>
      <div class="m-l-10px text-14px text-#8b8686eb box-orb flex items-center">
        <div class="text-14px">
          当前快照可创建数量:
          <span class="text-#e72f2fcc text-17px">{{ props.number }}</span>
        </div>
        <div class="m-l-10px text-#000 ovr flex items-center">
          <el-button :icon="Plus" circle size="small" @click="purchase = true" />
        </div>
      </div>
    </div>

    <!-- 表格展示 -->
    <el-scrollbar>
      <div class="min-w-600px">
        <el-table :data="networkList" style="width: 100%; margin-top: 20px">
          <el-table-column prop="id" label="ID" width="50" />
          <el-table-column prop="created_at" label="创建时间" />
          <el-table-column prop="note" label="快照备注" />
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button size="small" type="primary" :loading="delButton"
                @click="recover(scope.row.id)">恢复快照</el-button>
              <el-button size="small" type="danger" :loading="delButton"
                @click="handleDelete(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="flex-c m-t-20px">
          <el-pagination background layout="prev, pager, next,sizes" :total="total" :current-page="WebPage.page"
            :page-size="WebPage.count" :page-sizes="[1, 10, 20, 30]" @update:current-page="handleCurrentPageChange"
            @update:page-size="handlePageSizeChange" />
        </div>
      </div>
    </el-scrollbar>
    <el-dialog v-model="AddWeb" title="创建快照" width="600" draggable overflow>
      <div>
        <el-form ref="formRef" :model="formWeb" :rules="rules" label-width="auto" style="max-width: 600px">
          <el-form-item label="快照备注" prop="note">
            <el-input v-model="formWeb.note" placeholder="请输入快照备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="AddWeb = false">关闭</el-button>
          <el-button type="primary" :loading="loading" @click="submitForm">
            提交
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="purchase" title="购买快照" width="600" draggable overflow>
      <div style="display: flex; flex-wrap: wrap">
        <el-form ref="formRef" :model="paylist" label-width="150px">
          <el-form-item label="购买数量" prop="num" :rules="[
            {
              required: true,
              message: '请输入购买数量',
              trigger: 'blur'
            }
          ]">
            <el-input v-model="paylist.num" type="number" :min="1" :max="65535" placeholder="请输入购买数量" />
          </el-form-item>
          <el-form-item label="支付方式">
            <el-checkbox label="优先使用余额支付" checked disabled />
            <el-radio v-model="paylist.pay_type" :label="0" size="large">支付宝</el-radio>
            <el-radio v-model="paylist.pay_type" :label="1" size="large">微信</el-radio>
          </el-form-item>
          <el-form-item v-if="pay_src != ''" label="扫码支付">
            <el-image style="width: 100px; height: 100px" :src="pay_src" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="pay_money">
          <el-statistic title="总计结算金额：" :value="payprice + ' 元'" suffix="">
            <template #suffix>
              <el-icon style="vertical-align: -20px">
                <ChatLineRound />
              </el-icon>
            </template>
          </el-statistic>
        </div>
        <div class="dialog-footer">
          <el-button @click="purchase = false">关闭</el-button>
          <el-button type="primary" :loading="payloading" @click="topay">提交订单</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="pay_dialog" title="支付" style="width: 90%; height: 1000px">
      <iframe :srcdoc="pay_url" frameborder="0" style="width: 100%; height: 800px" />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, defineProps, defineEmits, watch } from "vue";
import { ElForm } from "element-plus";
import {
  getUserSnapshotList,
  createUserSnapshot,
  deleteSnapshot,
  recoverUserSnapshot,
  getSnapshotPrice,
  submitSnapshotOrder
} from "@/api/virtual";
import { pay_request } from "@/api/user";
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { message } from "@/utils/message";
const props = defineProps(["ID", "number"]);
const emit = defineEmits(["SetState"]);
onMounted(async () => {
  await getNetworkList();
});

const WebPage = reactive({
  page: 1,
  count: 10,
  instance_id: props.ID
});
const handleCurrentPageChange = async page => {
  WebPage.page = page;
  await getNetworkList();
};

const handlePageSizeChange = async count => {
  WebPage.count = count;
  await getNetworkList();
};

const networkList = ref([]);
const total = ref(0);
const getNetworkList = async () => {
  await getUserSnapshotList(WebPage).then(res => {
    console.log(res);
    networkList.value = res.data.data;
    total.value = res.data.count;
  });
};

// 添加数据卷信息
const formWeb = reactive({
  note: "" // 可选: allow/deny
});

// 表单验证规则
const rules = reactive<FormRules>({
  note: [{ required: true, message: "请输入快照备注", trigger: "change" }]
});

const formRef = ref<InstanceType<typeof ElForm>>();

const loading = ref(false);

const submitForm = async () => {
  try {
    loading.value = true; // 开始加载
    const valid = await formRef.value?.validate();
    if (valid) {
      console.log(formWeb);
      const res = await createUserSnapshot(formWeb, props.ID);
      console.log(res);
      if (res.data.code === 200) {
        message(res.data.data, { type: "success" });
        AddWeb.value = false;
      } else {
        message(res.data.msg, { type: "error" });
      }
      await getNetworkList();
    }
  } catch (error) {
    console.log(error);
    // message("提交表单时发生错误，请稍后再试。", { type: "error" });
  } finally {
    loading.value = false; // 结束加载
  }
};

const AddWeb = ref(false);
const delButton = ref(false);

// 删除快照
const handleDelete = async id => {
  delButton.value = true;
  await deleteSnapshot({ snapshot_id: id }, props.ID).then(async res => {
    if (res.data.code == 200) {
      message(res.data.data, { type: "success" });
      await getNetworkList();
    } else {
      message(res.data.data, { type: "error" });
    }
    delButton.value = false;
  });
};
//恢复快照
const recover = async id => {
  await recoverUserSnapshot({ snapshot_id: id }, props.ID).then(async res => {
    if (res.data.code == 200) {
      message(res.data.data, { type: "success" });
      emit("SetState", 123123);
    } else {
      message(res.data.data, { type: "error" });
    }
  });
};

// 购买快照
const purchase = ref(false);
const pay_src = ref("");
const paylist = reactive({
  pay_type: "3",
  num: "",
  instance_id: props.ID
});

// 购买价格
const payprice = ref("0");
// 获取价格
const purchaseVm = async () => {
  await getSnapshotPrice(paylist.num).then(res => {
    console.log(res);
    payprice.value = res.data.data.price;
  });
};

// 提交订单
const pay_dialog = ref(false);
const pay_url = ref("");
const payloading = ref(false);
const topay = async () => {
  payloading.value = true;
  await submitSnapshotOrder(paylist).then(res => {
    console.log(res);
    if (res.data.code == 200) {
      pay_request({
        pay_type: res.data.data.pay_type,
        trade_id: res.data.data.trade_id
      }).then(res => {
        console.log("支付信息", res);
        if (res.data.data.type == "html") {
          pay_url.value = res.data.data.html;
          pay_dialog.value = true;
        } else if (res.data.data.type == "img") {
          pay_src.value = res.data.data.img;
        } else {
          payloading.value = false;
          message("支付成功", { type: "success" });
          location.reload();
        }
      });
    }
  });
};
watch([paylist], () => {
  purchaseVm();
});
</script>

<style scoped>
.ovf {
  overflow-x: auto;
}

.box-orb {
  border-radius: 20px;
  font-weight: 700;
  border: 1px solid #d8ebff;
  background: #ebf5ff;
  padding: 2px 5px;
}
</style>
